<template>
  <el-form class="co-basic-form" ref="formElRef" :label-width="getLabelWidth" :model="formModel" v-bind="formAttr">
    <el-row v-if='formType === "view"' v-bind="rowAttr">
      <slot name="formTop"></slot>
      <template v-for="(item, index) in schemas">
        <co-form-item :key='"col_" + index' :formType='formType' :schema="item" @setFormModel="setFormModel" :size='size' :baseColProps="baseColProps" :bindValue='formModel[item.field]'></co-form-item>
      </template>
      <slot name="formBottom"></slot>
    </el-row>
    <el-row v-else v-bind="rowAttr">
      <template v-for="(item, index) in schemas">
        <!-- <el-row v-if="item.isBlock" :key='"col_" + index'>
          <co-form-item :key='"col_" + index' :schema="item" @setFormModel="setFormModel" :size='size' :baseColProps="baseColProps" :bindValue='formModel[item.field]' :formModel='formModel'></co-form-item>
        </el-row> -->
        <co-form-item :key='"col_" + index' :schema="item" @setFormModel="setFormModel" :size='size' :baseColProps="baseColProps" :bindValue='formModel[item.field]' :formModel='formModel'></co-form-item>
      </template>
      <co-form-action v-if='showActionButtonGroup' :baseColProps="baseColProps" v-bind='$props' :colSize='actColSize' v-on="$listeners"></co-form-action>
    </el-row>
  </el-form>
</template>

<script>
import CoFormItem from './components/co-form-item'
import CoFormAction from './components/co-form-action'
import util from '../../../assets/js/co-util'
export default {
  components: { CoFormItem, CoFormAction },
  props: {
    // 类型
    formType: {
      type: String,
      default: 'edit' // 'view', 'edit'
    },
    // 标签宽度  固定宽度
    labelWidth: {
      type: [String, Number]
    },
    fieldMapToTime: {
      type: Array,
      default: () => []
    },
    compact: {
      type: Boolean
    },
    // 表单配置规则
    schemas: {
      type: Array,
      default: () => []
    },
    autoSetPlaceHolder: {
      type: Boolean,
      default: true
    },
    submitOnReset: {
      type: Boolean
    },
    size: {
      type: String,
      default: 'medium'
    },
    // 禁用表单
    disabled: {
      type: String
    },
    emptySpan: {
      type: [Number, Object],
      default: 0
    },
    // 是否显示收起展开按钮
    showAdvancedButton: {
      type: Boolean,
      default: false
    },
    // 超过3行自动折叠
    autoAdvancedLine: {
      type: Number,
      default: 3
    },
    // 是否显示操作按钮
    showActionButtonGroup: {
      type: Boolean,
      default: true
    },
    // 操作列Col配置
    actionColOptions: {
      type: Object
    },
    // 显示重置按钮
    showResetButton: {
      type: Boolean,
      default: true
    },
    // 是否显示导出按钮
    showExportButton: {
      type: Boolean
    },
    // 是否有导出权限
    hasExportPermission: {
      type: Function,
      default: () => {
        return false
      }
    },

    // 导出按钮配置
    exportButtonOptions: {
      type: Object
    },
    // 是否聚焦第一个输入框，只在第一个表单项为input的时候作用
    autoFocusFirstItem: {
      type: Boolean
    },
    // 重置按钮配置
    resetButtonOptions: {
      type: Object
    },
    // 显示确认按钮
    showSubmitButton: {
      type: Boolean,
      default: true
    },
    // 确认按钮配置
    submitButtonOptions: {
      type: Object
    },

    // 自定义重置函数
    // resetFunc: {
    //   type: Function
    // },
    // submitFunc: {
    //   type: Function
    // },

    // 以下为默认props
    hideRequiredMark: {
      type: Boolean
    },
    labelCol: {
      type: Object
    },
    layout: {
      type: String
    },
    // propTypes.oneOf(['horizontal', 'vertical', 'inline']).def('horizontal'),
    labelAlign: {
      type: String
    },
    baseColProps: {
      type: [Object, Number]
    },
    actionColSize: {
      type: Number
    },
    formAttr: {
      type: Object
    },
    rowAttr: {
      type: Object
    },
    // 如果是搜索列表中的搜索条件，请配置使用co-table里面的 initFormData通过他传入进来
    initFormData: {
      type: Object
    }
  },
  data () {
    return {
      formModel: {}
    }
  },
  watch: {
    initFormData: {
      deep: true, // 深度监听设置为 true
      handler: function (newV, oldV) {
        this.setFieldsValue(newV)
      }
    }
  },
  computed: {
    getFormClass () {
      return ''
    },
    getLabelWidth () {
      if (this.labelWidth && !isNaN(this.labelWidth)) {
        return (this.labelWidth + 'px')
      }
      return (this.labelWidth ? this.labelWidth : '')
    },
    actColSize () {
      if (this.actionColSize) {
        return this.actionColSize
      }
      return 24 - ((this.schemas.length * 8) % 24)
    }
  },
  created () {
    if (this.initFormData) {
      this.setFieldsValue(this.initFormData)
    }
  },
  mounted () {
  },
  methods: {
    setFormModel (key, value) {
      this.$set(this.formModel, key, value)
    },
    handleRangeTimeValue (values) {
      if (!this.fieldMapToTime || !Array.isArray(this.fieldMapToTime)) {
        return values
      }
      for (const [
        field,
        [startTimeKey, endTimeKey],
        format
      ] of this.fieldMapToTime) {
        if (!field || !startTimeKey || !endTimeKey || !values[field]) {
          continue
        }
        const [startTime, endTime] = values[field]
        console.log('startTime, endTime', startTime, endTime)
        if (format) {
          values[startTimeKey] = util.formatDate(startTime, format)
          values[endTimeKey] = util.formatDate(endTime, format)
        } else {
          values[startTimeKey] = startTime
          values[endTimeKey] = endTime
        }
        delete values[field]
      }
      return values
    },
    getFormData () {
      let obj = JSON.parse(JSON.stringify(this.formModel))
      return this.handleRangeTimeValue(obj)
    },
    validate () {
      return new Promise((resolve, reject) => {
        this.$refs.formElRef.validate((valid) => {
          if (valid) {
            resolve(this.getFormData())
          } else {
            reject(this.getFormData())
          }
        })
      })
    },
    setFieldsValue (model) {
      // console.log('setFieldsValue=-model: ', model)
      for (let key in model) {
        this.setFormModel(key, model[key])
      }
    },
    resetFields () {
      this.$refs.formElRef.resetFields()
    }
  }
}
</script>
